<script setup>
import {computed, onBeforeMount, reactive, ref, toRefs} from 'vue'
import ClusterNamespaceSelector from './ClusterNamespaceSelector.vue';
import {getSecretListHandler} from '../../api/secret.js'
import {getServiceListHandler} from '../../api/service.js'
import { ElMessage,ElMessageBox  } from 'element-plus'
import StringOrNumber from './StringOrNumber.vue';
import Table from './Table.vue'
import { object2List, list2Object } from '../../utils/utils.js';
import ScheduleConfig from './scheduling/ScheduleConfig.vue'
import Volume from './scheduling/Volume.vue';
import Container from './scheduling/Container.vue';
// 导入pinia的数据
import { useItem } from '../../store/index.js';
import { storeToRefs } from 'pinia';
const activeName = ref('basic')
const labelActiveName = ref('controllerAnnos')
// 接收类型
const props = defineProps({
    resourceType: {
        type: String,
        default: "Deployment"
    },
    method: {
        type: String,
        default: "Create"
    }
})
// 定义资源操作的事件
const emits = defineEmits(['submit'])
const useItemer = useItem()
const data = reactive({
    clusterId: "",
    namespace: "",
    item: {
        metadata: {
            name: "",
            labels: {},
            annotations: {},
        },
        spec: {
            selector: {
                matchLabels: {},
            },
            replicas: 1,
            template: {
                metadata: {
                    labels: {},
                    annotations: {}
                },
                spec: {
                    imagePullSecrets: [],
                    dnsPolicy: "ClusterFirst",
                    hostNetwork: false
                }
            },
            strategy: {
                type: "RollingUpdate",
                rollingUpdate: {
                    maxSurge: "25%",
                    maxUnavailable: "25%"
                }
            }
        }
    },
    autoCreateService: true,
    registrySecretList: [],
    // https://kubernetes.io/zh-cn/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-policy
    dnsPolicyOptions: [
        {
            value: 'ClusterFirst',
            label: 'ClusterFirst'
        },
        {
            value: 'Default',
            label: 'Default'
        },
        {
            value: 'ClusterFirstWithHostNet',
            label: 'ClusterFirstWithHostNet'
        },
        {
            value: 'None',
            label: 'None'
        },
    ],
    options: {
        controllerAnnoList: [],
        controllerLabelList: [],
        podAnnoList: [],
        podLabelList: [],
        nodeSelectorList: [],
        serviceList: [],
        rules: {
            "name": [
                {required: true, message: '请输入资源名称', trigger: 'blur'}
            ],
            'serviceName': [
                {required: true, message: '请选择Service', trigger: 'blur'},
            ],
        },
    }
})
const itemRef = ref()
let autoCreateLabel = ref("true")
// 获取registry类型的secret 方法 
// type=kubernetes.io/dockerconfigjson
// labelSelector fieldSelector
const imagePullSecretsVisibleChanged = (visible) =>{
    if (!visible){return}
    getRegistrySecretList()
}

const getRegistrySecretList = ()=> {
    const getSecretListParas = {
        clusterId: data.clusterId,
        namespace: data.namespace,
        labelSelector: '',
        fieldSelector: 'type=kubernetes.io/dockerconfigjson'
    }
    getSecretListHandler(getSecretListParas).then(
        (res) => {
            // {name: xxx} 
            data.registrySecretList = []
          res.data.data.items.forEach((item)=>{
            if (data.registrySecretList == null || data.registrySecretList == undefined) {
                data.registrySecretList = []
            }
            data.registrySecretList.push({
                name: item.metadata.name
            })
          })
          console.log("secretList:", data.registrySecretList)
        }
      )
}
// namespace rollback
const namespaceRollback = (clusterId, namespace) => {
    console.log("namespace changed: ", clusterId, namespace)
    data.clusterId = clusterId
    data.namespace = namespace
    useItemer.clusterId = clusterId
    useItemer.namespace = namespace
    useItemer.item.metadata.namespace = namespace
    getRegistrySecretList()
    // 
}
const selectChanged = ()=> {
    console.log("item:", useItemer.item)
}

// 提示hostNetwork
const hostNetworkChanged = (val) => {
    if(val){
        ElMessage({
            message: "开启hostNetwork会直接占用宿主机网络和端口",
            type: 'warning',
        })
    }
}


const submitHandler = (tag) => {
    itemRef.value.validate((valid)=>{
            // valid => true
            if(valid){
                // 数据检验成功，回调函数去创建资源
                emits('submit',tag, data.autoCreateService)
            } else {
            ElMessage({
                        message: "请完善表单内容",
                        type: 'warning',
                    })
            }
        })
}
const submit = (tag)=> {
    //自动添加Service需要至少一个端口配置
    if (data.autoCreateService && tag != "yaml"){
        //判断是否有端口的配置
        let portCounter = 0
        useItemer.item.spec.template.spec.containers.forEach((c)=>{
            portCounter += c.ports.length
        })
        if(portCounter == 0){
            //没有添加端口的配置
            ElMessage.error("自动添加service需要添加的容器端口")
            return
        }
    }
    // console.log("container:", useItemer.item.spec.template.spec.containers)
    // 数据的二次处理
    // 1. 把list转成object
    let controllerAnnosObj = {}
    let controllerLabelsObj = {}
    let podAnnosObj = {}
    let podLabelsObj = {}
    if (autoCreateLabel.value == "true") {
        // 说明是自动生成label
        const obj = {
            app: useItemer.item.metadata.name
        }
        controllerAnnosObj = obj
        controllerLabelsObj = obj
        podAnnosObj = obj
        podLabelsObj = obj
    } else {
        controllerAnnosObj = list2Object(data.options.controllerAnnoList)
        controllerLabelsObj = list2Object(data.options.controllerLabelList)
        podAnnosObj = list2Object(data.options.podAnnoList)
        podLabelsObj = list2Object(data.options.podLabelList)
    }
    useItemer.item.metadata.labels = controllerLabelsObj
    useItemer.item.metadata.annotations = controllerAnnosObj
    if (props.resourceType != 'CronJob'){
        useItemer.item.spec.template.metadata.labels = podLabelsObj
        useItemer.item.spec.template.metadata.annotations = podAnnosObj
        useItemer.item.spec.selector.matchLabels = podLabelsObj
    }
    // 处理NodeSelector
    useItemer.item.spec.template.spec.nodeSelector = list2Object(data.options.nodeSelectorList)
    console.log("item:", useItemer.item)
    if(data.autoCreateService && props.resourceType == "StatefulSet"){
        useItemer.item.spec.serviceName = useItemer.item.metadata.name
    }
    submitHandler(tag)
}
//当绑定service的类型产生变化时调用查询service列表的接口
const radioChanged = ()=> {
    if (!data.autoCreateService) {useItemer.item.spec.serviceName = ''}
}
const visibleChanged = (visible)=> {
    if(!visible){return}
    const getListParas = {
        clusterId: data.clusterId,
        namespace: data.namespace,
        labelSelector: '',
        fieldSelector: ''
    }
    getServiceListHandler(getListParas).then(
        (res) => {
            data.options.serviceList = []
            // {name: xxx} 
            console.log("service List:", res)
            res.data.data.items.forEach((item)=>{
                if (item.spec.clusterIP == 'None'){
                    data.options.serviceList.push(item)
            }
          })
          
        }
      )
}
onBeforeMount(()=>{
    if (props.method != 'Create') {
        autoCreateService.value = false
        autoCreateLabel.value = 'false'
        // 把当前存在的label转成list
        console.log("当前的标签配置:", useItemer.item.metadata.labels)
        data.options.controllerAnnoList = object2List(useItemer.item.metadata.annotations)
        data.options.controllerLabelList = object2List(useItemer.item.metadata.labels)
        if (props.resourceType != 'CronJob'){
            data.options.podAnnoList = object2List(useItemer.item.spec.template.metadata.annotations)
            data.options.podLabelList = object2List(useItemer.item.spec.template.metadata.labels)
        }
        // 转换nodeSelector
        data.options.nodeSelectorList = object2List(useItemer.item.spec.template.spec.nodeSelector)
    }

})
const {registrySecretList,dnsPolicyOptions, autoCreateService,options} = toRefs(data)
const {item} = storeToRefs(useItem())
</script>

<template>
  <el-card class="box-card">
    <!-- 创建资源的表单 -->
    <el-form
    :model="item"
    ref="itemRef"
    label-width="140px"
    >
    <!-- 外层tabs -->
    <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="基本配置" name="basic" class="tab-pane" >
            <el-card class="box-card">
                <template #header>
                <div class="auto-space-between">
                    <!-- namespace 和 cluster选择器 -->
                    <div>
                        <ClusterNamespaceSelector
                        :cluster-readonly="props.method == 'Update'"
                        :namespace-readonly="props.method == 'Update'"
                        @namespaceChangedRollback="namespaceRollback"
                        ></ClusterNamespaceSelector>
                    </div>
                </div>
                </template>
                <div>
                    <!-- 基本配置 -->
                    <!-- 名称、副本数、密钥、DNS -->
                    <el-row :gutter="20">
                        <!-- 名称 -->
                        <el-col :span="6">
                            <el-form-item label="名称" prop="metadata.name" required :rules="options.rules.name">
                                <el-input :disabled="props.method == 'Update'" v-model.trim="item.metadata.name" style="width: 180px;" placeholder="请输入资源名称" />
                            </el-form-item>
                        </el-col>
                        <!-- 副本数 -->
                        <el-col :span="6" v-if="props.resourceType == 'Deployment' || props.resourceType == 'StatefulSet'">
                            <el-form-item label="副本数" prop="spec.replicas">
                                <el-input-number v-model="item.spec.replicas" :min="0" :max="100"/>
                            </el-form-item>
                        </el-col>
                        <!-- 私有仓库镜像密钥 -->
                        <el-col :span="6">
                            <el-form-item label="私有仓库密钥" prop="spec.template.spec.imagePullSecrets">
                                <el-select @visible-change="imagePullSecretsVisibleChanged" v-model="item.spec.template.spec.imagePullSecrets" value-key="name" multiple collapse-tags placeholder="绑定私有仓库密钥" >
                                    <el-option
                                    v-for="s in registrySecretList"
                                    :key="s.name"
                                    :label="s.name"
                                    :value="s"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="DNS策略" prop="spec.template.spec.dnsPolicy">
                                <el-select v-model="item.spec.template.spec.dnsPolicy"  placeholder="绑定私有仓库密钥">
                                    <el-option
                                    v-for="s in dnsPolicyOptions"
                                    :key="s.value"
                                    :label="s.label"
                                    :value="s.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 更新方式 hostNetwork -->
                    <el-row :gutter="20">
                        <!-- 定义一个插槽，用于不同控制器的更新方式的配置 -->
                         <slot name="strategy"></slot>
                       
                        <el-col :span="6" v-if="props.resourceType != 'CronJob'">
                            <el-form-item label="使用宿主机网络" prop="">
                                <el-switch
                                    v-model="item.spec.template.spec.hostNetwork"
                                    class="ml-2"
                                    style="--el-switch-on-color: #ff4949"
                                    @change="hostNetworkChanged"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 标签配置 自动添加service -->
                    <el-row :gutter="20">
                        <el-col :span="6" v-if="props.method != 'Update'">
                            <el-form-item label="标签及注释" prop="">
                                <el-radio-group v-model="autoCreateLabel" class="ml-4">
                                    <el-radio label="true" size="large">自动生成</el-radio>
                                    <el-radio label="false" size="large">手动配置</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="props.method != 'Update' && props.resourceType != 'CronJob'">
                            <el-form-item label="自动添加Service" prop=""  v-if="props.resourceType == 'Deployment' || props.resourceType == 'DaemonSet'">
                                <el-switch
                                    v-model="autoCreateService"
                                    class="ml-2"
                                />
                            </el-form-item>
                            <el-form-item label="绑定Service" prop=""  v-else="props.resourceType == 'StatefulSet'">
                                <el-radio-group @change="radioChanged()" v-model="autoCreateService" >
                                    <el-radio :label="true" size="large">自动生成Service</el-radio>
                                    <el-radio :label="false" size="large">选择已有的Service</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="!autoCreateService && props.resourceType == 'StatefulSet'">
                            <el-form-item label="选择service" required prop="spec.serviceName" :rules="options.rules.serviceName">
                                <el-select v-model="item.spec.serviceName" 
                                    placeholder="请选择绑定的Service"
                                    style="width: 180px;"
                                    @visible-change="visibleChanged()"
                                    >
                                    <el-option v-for="service in options.serviceList" 
                                    :key="service.metadata.name" 
                                    :label="service.metadata.name" 
                                    :value="service.metadata.name">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <slot name="specialConfig"></slot>
                    </el-row>
                </div>
            </el-card>
            <!-- 标签配置 -->
            <el-card v-if="autoCreateLabel == 'false'" style="margin-top: 20px;">
                <el-tabs tab-position="left" v-model="labelActiveName" class="demo-tabs" style="height: 240px;">
                    <el-tab-pane label="控制器注释" name="controllerAnnos">
                        <Table :list="options.controllerAnnoList"></Table>
                    </el-tab-pane>
                    <el-tab-pane label="控制器标签" name="controllerLabels">
                        <Table :list="options.controllerLabelList"></Table>
                    </el-tab-pane>
                    <el-tab-pane v-if="props.resourceType != 'CronJob'" label="Pod注释" name="podAnnos">
                        <Table :list="options.podAnnoList"></Table>
                    </el-tab-pane>
                    <el-tab-pane v-if="props.resourceType != 'CronJob'" label="Pod标签" name="PodLabels">
                        <Table :readonly="props.method=='Update'" :list="options.podLabelList"></Table>
                    </el-tab-pane>
                </el-tabs>
            </el-card>

        </el-tab-pane>
        <!-- 节点选择器 -->
        <el-tab-pane label="高级配置" name="affinity"  class="tab-pane" >
            <ScheduleConfig :list="options.nodeSelectorList"></ScheduleConfig>
        </el-tab-pane>
        <el-tab-pane label="存储配置" name="volume"  class="tab-pane" >
            <Volume></Volume>
        </el-tab-pane>
        <el-tab-pane label="容器配置" name="container"  class="tab-pane" >
            <Container :method="props.method" :resource-type="props.resourceType"></Container>
        </el-tab-pane>
        <el-tab-pane label="初始化容器" name="init-container"  class="tab-pane" >
            <Container :method="props.method" :resource-type="props.resourceType" container-type="init"></Container>
        </el-tab-pane>
    </el-tabs>
    <span style="display: block; margin-top: 30px;" class="span-button">
        <el-button @click="submit('yaml')">Yaml</el-button>
        <el-button @click="submit()" type="primary">
            {{ props.method=="Update"?"更新":"创建" }}
        </el-button>
    </span>
    </el-form>
  </el-card>
</template>

<style scoped>
.tab-pane {
    height: 600px;
}
</style>
